//
//  LoginViewController.m
//  ICrEAM
//
//  Created by mac on 16/10/19.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LoginViewController.h"
#import "MainViewController.h"
#import "LoginAction.h"
#import "YTKNetworkConfig.h"
#import "ICrEAMUser.h"
#import "AppDelegate.h"
#import "CofigViewController.h"
#import "PushAction.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UIView *userView;
@property (weak, nonatomic) IBOutlet UIView *passWordView;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn; //登陆按钮
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField; //密码框
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;
@property (weak, nonatomic) IBOutlet UITextField *userTextField; //用户名
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftConstraint;
@property (weak, nonatomic) IBOutlet UIImageView *bgImageView;
@property (nonatomic,strong)LoginAction *action;
@end

@implementation LoginViewController
#pragma mark 登陆
- (IBAction)loginAction:(id)sender {
    
    if (IsStrEmpty(self.userTextField.text)||IsStrEmpty(self.passwordTextField.text)) {
        [self showText:@"请填写用户名／密码"];
        return;
    }
   
        NSString * key=@"CFBundleShortVersionString";
        NSString *  currentVersion= [NSBundle mainBundle].infoDictionary[key];
    _action=[[LoginAction alloc]init];
        _action.vession=currentVersion;
        _action.userName=self.userTextField.text;
        _action.password=self.passwordTextField.text;
    NSString *iosVession;
    if ([[UIDevice currentDevice].systemVersion floatValue]>=9.0) {
        iosVession=@"9";
    }else{
        iosVession=@"8";
    }
    _action.iosVession=iosVession;
    [self requestDataWithAction:_action haveHud:YES showError:NO  success:^(__kindof YTKBaseRequest *request) {
        
//         Set-Cookie	JSESSIONID=0CAAA6061EE4B7D3C3E664BE70379D1C; Path=/INFO_ICREAM_WEB
//     NSDictionary *heads=request.requestOperation.response.allHeaderFields;
        id  keyValues = [request.responseString mj_JSONObject];
        if (![keyValues isKindOfClass:[NSDictionary class]]) {
    
            return;
        }
        if (!IsStrEmpty(keyValues[@"DOWNLOAD_URL"])) {
              NSString *url=keyValues[@"DOWNLOAD_URL"];
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services:///?action=download-manifest&url=%@",url]]]) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services:///?action=download-manifest&url=%@",url]]];
                    return;
                
            }
      /*
            UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:@"升级到最新版本" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *sureAction=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSString *url=keyValues[@"DOWNLOAD_URL"];
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services:///?action=download-manifest&url=%@",url]]]) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services:///?action=download-manifest&url=%@",url]]];
                    
                }
                
            }];
            
            [alert addAction:sureAction];
            
            [self presentViewController:alert animated:YES completion:nil];
            return;
       */
        }
      
    
#pragma mark 设置推送
        PushAction *action=[[PushAction alloc]init];
        if ([ICrEAMUser shareICrEAMUser].deviceToken) {
            action.token=[ICrEAMUser shareICrEAMUser].deviceToken;
        }
        [action startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest *request) {
            DDLog(@"%@-----%@",request.requestUrl,request.baseUrl);
            
        } failure:^(__kindof YTKBaseRequest *request) {
            
        }];
        
        NSDictionary *dic=keyValues[@"TM_USER"];
        ICrEAMUser *user=[ICrEAMUser shareICrEAMUser];
        user.account=self.userTextField.text;
        user.passWord=self.passwordTextField.text;
        user.asc_name=dic[@"ASC_NAME"];
        user.consultant=dic[@"CONSULTANT"];
        user.employee_NO=dic[@"EMPLOYEE_NO"];
        user.net_code=dic[@"NET_CODE"];
        user.org_code=dic[@"ORG_CODE"];
        user.positon_code=dic[@"POSITION_CODE"];
        user.user_name=dic[@"USER_NAME"];
        user.IS_SERVICE_ADVISOR=dic[@"IS_SERVICE_ADVISOR"];
        user.IS_WORKSHOP_MASTER=dic[@"IS_WORKSHOP_MASTER"];
        user.IS_SERVICE_ADVISOR_MASTER=dic[@"IS_SERVICE_ADVISOR_MASTER"];
        user.BALANCED_ACCURACY = dic[@"BALANCED_ACCURACY"];
        user.BALANCED_WAY = dic[@"BALANCED_WAY"];
        user.balance_range = dic[@"BALANCED_RANGE"];
        if ([ICrEAMUser shareICrEAMUser].userType==NoneType) {
            [self showText:@"未获取到权限菜单！"];
            return;
        }
        if(!user.BALANCED_WAY){
        
            user.BALANCED_WAY = @"21381001";
        
        }
        
        
        
        
        
        MainViewController  *main=[[MainViewController alloc]init];
        main.hideNav=YES;
//        [self.navigationController pushViewController:main animated:YES];
        [self.view endEditing:YES];
        [AppDelegate currentAppDelegate].window.rootViewController= [[UINavigationController alloc]initWithRootViewController:main];

    } failure:^(__kindof YTKBaseRequest *request) {
        [self showText:@"获取服务器信息失败"];
    }];
    
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField==self.userTextField) {
        [self.userTextField resignFirstResponder];
        [self.passwordTextField becomeFirstResponder];
    }else{
        [self.view endEditing:YES];
    }
    return YES;
}
- (IBAction)dismiss:(id)sender {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
       
        CofigViewController *config=[[CofigViewController alloc]init];
//        config.isPresent=YES;
        config.ipText=[[[ICreamCache sharedInstance] stringForKey:kIPPath] mutableCopy];

        config.hideSuspendView=YES;
        [[ICreamCache sharedInstance] removeDataForKey:kIPPath];
        [[ICreamCache sharedInstance] removeDataForKey:isVWPath];
        [[ICreamCache sharedInstance] removeDataForKey:HomePagePath];
         [[ICreamCache sharedInstance] removeDataForKey:kHotLine];
//        [self presentViewController:config animated:YES completion:^(){
//            
//        }];
        [UIApplication sharedApplication].keyWindow.rootViewController=config;
        
    }
    
}
// 设置网络请求
- (void)setupNetworkConfig
{
    YTKNetworkConfig *config = [YTKNetworkConfig sharedInstance];
    config.baseUrl =[NSString stringWithFormat:@"http://%@",[[ICreamCache sharedInstance] stringForKey:kIPPath]];    
}

- (void)viewDidLoad {
    self.hideRightNavItem=YES;
    [super viewDidLoad];
    self.hideSuspendView=YES;
    if ([ICrEAMTool isVW]) {
        self.leftConstraint.constant=184;
        self.rightConstraint.constant=184;
        self.bgImageView.image=[UIImage imageNamed:@"dazhongBg_image"];
        self.logoImageView.image=[UIImage imageNamed:@"dazhongLogo"];
    }else{
        self.logoImageView.image=[UIImage imageNamed:@"sikedaLogo"];
        self.leftConstraint.constant=0;
        self.rightConstraint.constant=0;
        self.bgImageView.image=[UIImage imageNamed:@"sikedaBg_img"];
        self.loginBtn.backgroundColor= KSKBgColor;
    }
    self.title=@"登陆";
    self.edgesForExtendedLayout=UIRectEdgeNone;
    self.userView.layer.cornerRadius=10;
    self.userView.layer.masksToBounds=YES;
    //    self.userView.layer.borderWidth=1;
    
    self.passWordView.layer.cornerRadius=10;
    self.passWordView.layer.masksToBounds=YES;
    
    [self setupNetworkConfig];
    
    //
  
    // Do any additional setup after loading the view from its nib.
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
